<template>
  <el-dialog
    title="素材库"
    :visible.sync="dialogImages"
    width="940px"
    :before-close="handleClose"
    class="material"
  >
    <div class="material-con" style="text-align: center;">
      <div class="menu-left">
        <div
          v-for="(item, index) in optionArr"
          :key="index"
          class="menu-item"
          :class="name == item.name ? 'optionCss' : ''"
          @click="optionTag(item)"
        >
          {{ item.name }}
        </div>

        <div
          v-for="(items, index) in rootlist"
          :key="index"
          class="menu-item"
          style="margin-top: 10px; background:#f8f8f8"
        >
          {{ items.group_name }}
        </div>
        <div id="container" class="up-pic">
          <el-button size="mini" style="position: relative;">
            <big>+</big>上传
            <input
              id="upPic"
              ref="inputUpload"
              type="file"
              multiple="multiple"
              style="position: absolute;
                    top: 0;
                    left: 0;
                    opacity: 0;
                    width: 62px;"
              @change="inputUpload($event)"
            />
          </el-button>
          <span class="desc">{{ msg }}</span>
        </div>
      </div>
      <div class="imgupdate-box">
        <div v-if="listData.length > 0">
          <div v-if="fileType == 1">
            <div
              v-for="(item, index) in listData"
              :key="index"
              class="chlids"
              @click="selectImg(index)"
            >
              <span class="del-chlids" @click="deleteItem(item.file_id)">
                <big>x</big>
              </span>
              <img
                :src="
                  $store.state.qiniu + item.file_path + $store.state.imgRotate
                "
                style="width:100%;height:120px;"
                :class="{ currentImg: currentImgIndex === index }"
              />
              <p>{{ item.file_name }}</p>
            </div>
          </div>

          <div v-if="fileType == 2">
            <div
              v-for="(item, index) in listData"
              :key="index"
              class="chlids"
              style="width:200px;"
              @click="selectVideo(index)"
            >
              <span class="del-chlids" @click="deleteItem(item.file_id)">
                <big>x</big>
              </span>

              <video
                ref="videosM"
                width="100%"
                height="120px"
                controls="controls"
                controlsList="nodownload"
                poster=""
                :src="
                  $store.state.qiniu + item.file_path + $store.state.imgRotate
                "
                :class="{ currentImg: currentImgIndex === index }"
                @play="plays(index)"
              ></video>

              <p>{{ item.file_name }}</p>
            </div>
          </div>
        </div>
        <div
          v-if="listData.length == 0"
          class="content"
          style="    color: #909399;
    font-size: 16px;
    text-align: center;
    line-height: 350px;"
        >
          暂无资源！
        </div>
      </div>
      <div v-if="listData.length > 0" class="imgupdate-pagination">
        <el-pagination
          :page-size="pageshow"
          :current-page="pages"
          layout="prev, pager, next,jumper"
          :total="totals"
          @current-change="changes"
        >
        </el-pagination>
      </div>
      <div v-if="useBtn" class="imgupdate-btn">
        <el-button size="small" @click="handleClose">取 消</el-button>
        <el-button size="small" type="primary" @click="addImg">确 定</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import * as qiniu from "qiniu-js";
import {
  sckDELETE,
  sckGETLIST,
  sckGETLISTGROUP,
  UP_TOKEN,
  QINIUUPLOAD
} from "./service";

export default {
  props: {
    dialogImages: {
      type: Boolean,
      default: false
    },
    useBtn: {
      type: Boolean,
      required: true
    },
    useType: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      group_id: "",
      uploader: {},
      listData: [],
      currentImgIndex: 0,
      rootlist: [],
      totals: 0,
      pages: 1,
      fileType: 1,
      pageshow: 10,
      name: "我的图片",
      msg: "请上传图片",
      option: [
        {
          name: "我的图片",
          msg: "请上传图片",
          file_type: 1,
          pageshow: 10,
          useType: "img"
        },
        {
          name: "我的视频",
          msg: "请上传视频",
          file_type: 2,
          pageshow: 6,
          useType: "video"
        }
      ],
      qnToken: ""
    };
  },
  computed: {
    optionArr() {
      let arr = [];
      switch (this.useType) {
        case "all":
          arr = this.option;
          break;
        case "img":
          arr = [this.option[0]];
          break;
        case "video":
          arr = [this.option[1]];
          break;
      }
      return arr;
    }
  },
  watch: {
    dialogImages(v) {
      if (v) {
        switch (this.useType) {
          case "all":
            this.optionTag(this.optionArr[0]);
            break;
          case "img":
            this.optionTag(this.optionArr[0]);
            break;
          case "video":
            this.optionTag(this.optionArr[1]);
            break;
        }
        if (this.$store.state.imgInitPgae) {
          this.pages = this.$store.state.imgInitPgae;
        }
      }
    }
  },
  created() {
    this.qiniuTag();
    this.getGroup();
  },
  methods: {
    optionTag(e) {
      this.name = e.name;
      this.msg = e.msg;
      this.fileType = e.file_type;
      this.totals = 0;
      this.pageshow = e.pageshow;
      this.getList();
    },

    selectImg(index) {
      this.currentImgIndex = index;
    },
    selectVideo(index) {
      this.$refs.videosM.forEach((ele, e) => {
        if (index !== e) {
          ele.pause();
        }
      });
      this.currentImgIndex = index;
    },
    handleClose() {
      this.$emit("close");
      if (this.fileType === 2) {
        this.$refs.videosM.forEach(ele => {
          ele.pause();
        });
      }
    },
    plays(index) {
      this.$refs.videosM.forEach((ele, e) => {
        if (index !== e) {
          ele.pause();
        }
      });
      this.currentImgIndex = index;
    },
    addImg() {
      this.$emit("close", this.listData[this.currentImgIndex]);
      this.$emit("lunboChangeImg", this.listData[this.currentImgIndex]);
      if (this.fileType === 2) {
        this.$refs.videosM.forEach(ele => {
          ele.pause();
        });
      }
    },

    inputUpload(e) {
      let file = Array.prototype.slice.call(e.target.files);
      let that = this;
      file.forEach(ele => {
        let lock = this.beforeUpload(ele);
        if (!lock) {
          return;
        }
        let random1 = parseInt(Math.random() * 100000);
        let random2 = parseInt(Math.random() * 100000);
        let time = new Date().getTime();
        let d = ele.name.lastIndexOf(".");
        let hz = ele.name.substring(d);
        let fileName = "" + random1 + random2 + time + hz;

        let observable = qiniu.upload(ele, fileName, this.qnToken);
        observable.subscribe({
          next() {},
          // eslint-disable-next-line handle-callback-err
          error() {
            that.$message.error("上传失败！");
          },
          complete(res) {
            that.qnUpload(ele.name, res.key, ele.size);
          }
        });
      });
      this.$refs.inputUpload.value = null;
    },
    beforeUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isGIF = file.type === "image/gif";
      const isSVG = file.type === "image/svg+xml";
      const isMP4 = file.type === "video/mp4";
      if (this.fileType === 1 && !isJPG && !isPNG && !isSVG && !isGIF) {
        this.$message.error("上传图片只能是 JPG、PNG、SVG 或 GIF 格式!");
        return false;
      }
      if (this.fileType === 2 && !isMP4) {
        this.$message.error("上传视频只能是 MP4 格式!");
        return false;
      }
      this.$message("正在上传！");

      return true;
    },
    async qnUpload(fileName, filePath, fileSize) {
      await QINIUUPLOAD({
        group_id: this.group_id,
        file_type: this.fileType,
        file_name: fileName,
        file_path: filePath,
        file_size: fileSize
      }).then(({ code }) => {
        if (code === 200) {
          this.getList();
          this.$message.success("上传成功！");
        } else {
          this.$message.error("上传失败！");
        }
      });
    },

    changes(page) {
      this.$store.commit("imgInitPgae", page);
      this.pages = page;
      this.getList();
    },
    async getList() {
      this.listData = [];
      await sckGETLIST({
        pageshow: this.pageshow,
        page: this.pages,
        group_id: this.group_id,
        file_type: this.fileType
      }).then(({ code, data }) => {
        if (code === 200) {
          this.totals = data.length;
          this.listData = Array.prototype.slice.call(data.list);
        }
      });
    },
    async deleteItem(id) {
      await sckDELETE({
        group_id: this.group_id,
        file_id: id,
        file_type: this.fileType
      }).then(({ code, msg }) => {
        if (code === 200) {
          this.$message.success(msg);
          this.getList();
        }
      });
    },
    async qiniuTag() {
      await UP_TOKEN().then(({ data }) => {
        this.qnToken = data;
      });
    },
    async getGroup() {
      await sckGETLISTGROUP({
        file_type: this.fileType
      }).then(({ code, data }) => {
        if (code === 200) {
          this.group_id = data[0][0].group_id;
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.imgupdate-box {
  width: 100%;
  height: 368px;
  .chlids {
    width: 120px;
    height: 164px;
    position: relative;
    margin: 6px;
    float: left;
    p {
      height: 40px;
      width: 100%;
      text-overflow: -o-ellipsis-lastline;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      line-clamp: 2;
      -webkit-box-orient: vertical;
      text-align: left;
    }
    &:hover .del-chlids {
      display: inline-block;
    }
    .del-chlids {
      width: 26px;
      height: 26px;
      line-height: 22px;
      text-align: center;
      color: #fff;
      background: #909399;
      border-radius: 50%;
      position: absolute;
      right: 6px;
      top: 6px;
      display: none;
      z-index: 100;
      cursor: pointer;
    }
    .currentImg {
      border: 2px solid #00ffff !important;
    }
  }
}
.imgupdate-pagination {
  text-align: center;
  padding: 2px 0;
}
.imgupdate-btn {
  text-align: right;
  padding-right: 12px;
  margin-top: 12px;
}
</style>

<style>
.optionCss {
  background: #2589ff;
  color: #fff !important;
}
.videos video::-webkit-media-controls-current-time-display {
  font-size: 12px;
  height: 22px;
  display: none;
}
.videos video::-webkit-media-controls-time-remaining-display {
  font-size: 12px;
  height: 22px;
  display: none;
}
/* .videos video::-webkit-media-controls-overlay-play-button div{
      background-size: 16px 16px !important;
      border-radius: 0 !important;
    } */
.videos video::-webkit-media-controls-timeline {
  padding-bottom: 8px;
}
.videos video::-webkit-media-controls-mute-button {
  width: 14px;
  height: 14px;
  background-size: 16px 16px;
  display: none;
}
.videos video::-webkit-media-controls-fullscreen-button {
  width: 14px;
  height: 14px;
  background-size: 16px 16px;
  display: none;
}
</style>
